<template>
    <div class="personal-container">
        <el-form class="personal-form" :model="user" ref="userForm" label-width="120px" :rules="rules">
            <!-- 头像预览区域 -->
            <div class="avatar-section">
                <div class="avatar-wrapper">
                    <img class="avatar-preview" :src="user.headPicture || defaultAvatar" alt="用户头像"
                        @error="handleAvatarError">
                    <div class="avatar-overlay" v-if="!user.headPicture">
                        <i class="el-icon-picture-outline"></i>
                        <span>暂无头像</span>
                    </div>
                </div>
                <div class="avatar-actions">
                    <input type="file" accept="image/*" hidden ref="iptRef" @change="onFileChange">
                    <el-button type="primary" icon="el-icon-picture-outline" @click="chooseImg"
                        :loading="uploadLoading">
                        更换头像
                    </el-button>
                    <p class="upload-tip">支持 JPG、PNG 格式，大小不超过 2MB</p>
                </div>
            </div>

            <!-- 表单字段区域 -->
            <div class="form-section">
                <el-form-item prop="username" label="用户名">
                    <el-input v-model="user.name" placeholder="请输入用户名" clearable maxlength="20" show-word-limit />
                </el-form-item>

                <el-form-item prop="password" label="密码">
                    <el-input v-model="user.password" type="password" placeholder="请输入新密码" show-password clearable />
                    <div class="tip-text">如不需修改密码，请留空</div>
                </el-form-item>

                <el-form-item prop="mobilePhone" label="手机号">
                    <el-input v-model="user.mobilePhone" placeholder="请输入手机号" clearable maxlength="11" />
                </el-form-item>

                <el-form-item prop="sex" label="性别">
                    <el-select v-model="user.sex" placeholder="请选择性别" clearable>
                        <el-option label="男" value="male" />
                        <el-option label="女" value="female" />
                    </el-select>
                </el-form-item>

                <el-form-item prop="Career" label="职业">
                    <el-input v-model="user.Career" placeholder="请输入职业" clearable maxlength="50" />
                </el-form-item>

                <el-form-item prop="address" label="地址">
                    <el-input v-model="user.address" placeholder="请输入详细地址" clearable maxlength="100" show-word-limit />
                </el-form-item>

                <el-form-item class="submit-item">
                    <el-button type="success" @click="submit" :loading="submitLoading" style="width: 200px">
                        {{ submitLoading ? '保存中...' : '保存修改' }}
                    </el-button>
                    <el-button @click="resetForm" style="width: 100px; margin-left: 20px;">
                        重置
                    </el-button>
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script>
import { getUserById, getUser, UpUser } from '@/api/admin/User'
import { upload } from '@/api/common/common'

export default {
    name: 'UserPersonal',
    data() {
        return {
            user: {
                mobilePhone: '',
                sex: '',
                id: '',
                address: '',
                name: '',
                headPicture: '',
                password: '',
                Career: ''
            },
            defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
            uploadLoading: false,
            submitLoading: false,
            originalUser: null,
            rules: {
                name: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 20, message: '用户名长度为 2 到 20 个字符', trigger: 'blur' }
                ],
                mobilePhone: [
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        chooseImg() {
            this.$refs.iptRef.click()
        },

        async onFileChange(e) {
            const file = e.target.files[0]
            if (!file) return

            if (!file.type.startsWith('image/')) {
                this.$message.error('请选择图片文件')
                return
            }

            if (file.size > 2 * 1024 * 1024) {
                this.$message.error('图片大小不能超过 2MB')
                return
            }

            this.uploadLoading = true
            try {
                const response = await upload(file)
                this.user.headPicture = response
                this.$message.success('头像上传成功')
            } catch (error) {
                this.$message.error('头像上传失败')
                console.error('Upload error:', error)
            } finally {
                this.uploadLoading = false
                e.target.value = ''
            }
        },

        formatImagePath(path) {
            if (!path) return this.defaultAvatar;

            console.log('原始路径:', path);
            // 清理路径中的引号和前后空格
            let cleanPath = path.replace(/["']/g, '').trim();
            console.log('清理后路径:', cleanPath);

            // 匹配所有系统路径（Windows: C:\a\b.png，Linux: /home/a/b.png），提取最后一个 / 或 \ 后的文件名
            const fileNameMatch = cleanPath.match(/([^\\/]+)\.(\w+)$/);
            if (fileNameMatch && fileNameMatch[1] && fileNameMatch[2]) {
                const fileName = `${fileNameMatch[1]}.${fileNameMatch[2]}`;
                console.log('提取的文件名:', fileName);
                const imageUrl = `http://localhost:8090/images/${fileName}`;
                console.log('生成的图片URL:', imageUrl);
                return imageUrl;
            }

            return cleanPath || this.defaultAvatar;
        },

        async load() {
            try {
                const user = JSON.parse(getUser())
                const response = await getUserById(user.id)
                const userData = response.data.data

                console.log('=== 加载用户信息 ===')
                console.log('数据库中的头像路径:', userData.headPicture)

                // 处理头像路径
                const processedHeadPicture = this.formatImagePath(userData.headPicture)

                this.user = {
                    mobilePhone: userData.mobilePhone || '',
                    sex: userData.sex || '',
                    id: userData.id || '',
                    address: userData.address || '',
                    name: userData.name || '',
                    headPicture: processedHeadPicture,
                    password: '',
                    Career: userData.Career || ''
                }

                console.log('最终使用的头像URL:', this.user.headPicture)

                // 保存原始数据用于重置
                this.originalUser = { ...this.user }

            } catch (error) {
                this.$message.error('加载用户信息失败')
                console.error('Load error:', error)
            }
        },

        handleAvatarError(event) {
            console.error('头像加载失败，使用默认头像')
            event.target.src = this.defaultAvatar
        },

        async submit() {
            try {
                await this.$refs.userForm.validate()

                this.submitLoading = true
                this.user.id = JSON.parse(getUser()).id

                const submitData = { ...this.user }
                if (!submitData.password) {
                    delete submitData.password
                }

                await UpUser(submitData)
                this.$message.success('个人信息更新成功')

                const updatedUser = { ...JSON.parse(getUser()), ...submitData }
                localStorage.setItem('user', JSON.stringify(updatedUser))

                this.$router.push('/home')
            } catch (error) {
                if (error.response) {
                    this.$message.error(error.response.data.message || '更新失败')
                } else if (error instanceof Error) {
                    return
                } else {
                    this.$message.error('更新失败，请重试')
                }
                console.error('Submit error:', error)
            } finally {
                this.submitLoading = false
            }
        },

        resetForm() {
            if (this.originalUser) {
                this.user = { ...this.originalUser, password: '' }
            }
            this.$refs.userForm.clearValidate()
            this.$message.info('表单已重置')
        }
    },

    mounted() {
        this.load()
    }
}
</script>

<style lang="less" scoped>
/* 样式保持不变 */
.personal-container {
    padding: 30px;
    background: #f5f7fa;
    min-height: calc(100vh - 60px);
}

.personal-form {
    display: flex;
    gap: 40px;
    max-width: 1200px;
    margin: 0 auto;
    padding: 30px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.avatar-section {
    width: 300px;
    text-align: center;
    padding: 20px;

    .avatar-wrapper {
        border: 2px dashed #dcdfe6;
        border-radius: 12px;
        padding: 15px;
        margin-bottom: 25px;
        position: relative;
        background: #fafbfc;
        transition: all 0.3s ease;

        &:hover {
            border-color: #409eff;
        }

        .avatar-preview {
            width: 100%;
            height: 280px;
            border-radius: 8px;
            object-fit: cover;
            background: linear-gradient(145deg, #f0f2f5, #e4e7ed);
        }

        .avatar-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: #909399;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 8px;

            .el-icon-picture-outline {
                font-size: 48px;
                margin-bottom: 10px;
            }

            span {
                font-size: 14px;
            }
        }
    }

    .avatar-actions {
        display: flex;
        flex-direction: column;
        gap: 15px;

        .upload-tip {
            font-size: 12px;
            color: #909399;
            margin: 0;
            line-height: 1.4;
        }
    }
}

.form-section {
    flex: 1;
    padding: 10px 0;

    .el-form-item {
        margin-bottom: 24px;

        &::v-deep .el-form-item__label {
            color: #606266;
            font-weight: 600;
            font-size: 14px;
        }

        .el-input,
        .el-select {
            width: 100%;
            max-width: 400px;
        }

        .tip-text {
            font-size: 12px;
            color: #909399;
            margin-top: 4px;
        }
    }
}

.submit-item {
    margin-top: 40px;
    text-align: center;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;

    &::v-deep .el-form-item__content {
        display: flex;
        justify-content: center;
        align-items: center;
    }
}

@media (max-width: 768px) {
    .personal-form {
        flex-direction: column;
        gap: 30px;
        padding: 20px;
    }

    .avatar-section {
        width: 100%;
        max-width: 300px;
        margin: 0 auto;
    }
}
</style>